#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "functions.h"
#include "tokens.h"


int main(int argc, char *argv[])
{
	char hostname[128];
	char curWorkDir[1024];
	char * pUsername;
    int a = 0;
    int b = 0;
    int command_found=0;
	FUNC_TYPE func_return = 0;

    char *tokens[50]={0};
    char *setshell[3]={0};
	int *num_tokens = (int *) malloc(sizeof(int));
	unsigned int cmd;


	//initialize shell environmental variable
	getcwd(curWorkDir, sizeof(curWorkDir));
	setshell[1] = "shell";
	setshell[2] = curWorkDir;
	setenv_func(2,setshell);


	do{
		gethostname(hostname, sizeof(hostname));
	    getcwd(curWorkDir, sizeof(curWorkDir));
        pUsername = getenv("USERNAME");

		printf("%s@%s %s > ",pUsername,hostname,curWorkDir);
	    cmd = get_tokens(num_tokens, tokens);
	  //  background_func(*num_tokens, tokens);
	  //  cmd = get_tokens(num_tokens, tokens);
		if (cmd == 69) {
			func_return = pipetrial_func(*num_tokens, tokens);
		} else if (cmd == 31) {
			func_return = background_func(*num_tokens, tokens);
		} else  {
	    if(tokens[0]!=NULL){
	    	command_found=0;
	    	for(a=0;a<8;a++)
	    	{
	    		if(!strcmp(tokens[0],mainCommandList[a].CommandName)){
	    			command_found=1;
	    			if (mainCommandList[a].FunctionName != API_PTR) // ??
	    			{
	    				func_return = mainCommandList[a].FunctionName(*num_tokens, tokens);
	    				break;
	    			}


	    		}
	    	}

	    	if(command_found==0) {
	    	//if command not found, print all arguments
	    	//	for(b=0; tokens[b]!= NULL; b++)
	    	//	{
	    	//		printf ("%s\n",tokens[b]);
	    	//	}

	    	//remove below comments and comment out "external_func" to try pipe functionality
	    	 // pipetrial_func(*num_tokens, tokens);
	    		external_func(*num_tokens, tokens);
	    	}
	    } }
	} while( func_return != 1 );

	printf("\n");


	return 0;
}
